﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;

public class PacmanMove : MonoBehaviour {
	public float speed = 0.4f;
 
	public float sensitivityX = 1F;  


	// Use this for initialization
	void Start () {
		Cursor.visible = false;
		Cursor.lockState = CursorLockMode.Locked;
	}
	
	// Update is called once per frame
	void Update () {
		
	}

	void FixedUpdate() {
		Vector2 dt = Vector2.zero;
		if (Input.GetKey (KeyCode.W)) {
			dt += Vector2.up;
		} 
		if (Input.GetKey (KeyCode.D)) {
			dt += Vector2.right;
		} 
		if (Input.GetKey (KeyCode.S)) {
			dt += Vector2.down;
		} 
		if (Input.GetKey (KeyCode.A)) {
			dt += Vector2.left;
		}
		transform.Rotate(0, 0, -Input.GetAxis("Mouse X") * sensitivityX);  
		if (dt != Vector2.zero) {		
			dt = RotationMatrix (dt, -transform.eulerAngles.z);	
			GetComponent<Rigidbody2D> ().MovePosition(Vector2.MoveTowards(transform.position, (Vector2)transform.position + dt, speed));
		}
	}   
	void LateUpdate () {

		Vector2 forward = RotationMatrix (Vector2.up, -transform.eulerAngles.z);	
		Vector2 forwardPos = (Vector2)transform.position + forward * 30;
		Camera.main.transform.position = new Vector3 (forwardPos.x, forwardPos.y, Camera.main.transform.position.z);
		Camera.main.transform.rotation = transform.rotation;

	}
	/// <summary>
	/// 旋转向量，使其方向改变，大小不变
	/// </summary>
	/// <param name="v">需要旋转的向量</param>
	/// <param name="angle">旋转的角度</param>
	/// <returns>旋转后的向量</returns>
	private Vector2 RotationMatrix(Vector2 v, float angle)
	{
		var x = v.x;
		var y = v.y;
		var sin = Math.Sin(Math.PI * angle / 180);
		var cos = Math.Cos(Math.PI * angle / 180);
		var newX = x * cos + y * sin;
		var newY = x * -sin + y * cos;
		return new Vector2((float)newX, (float)newY);
	}
}
